import axios from "axios"
import router from "./router";
import Element, {Loading} from "element-ui"

axios.defaults.baseURL = "http://fgba.top:8084/library"

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }
})

request.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem("token");

    return config;
})
let flag = false;
request.interceptors.response.use(response => {
    let res = response.data;
    flag = false;
    if (res.code === "00000") {
        return response
    } else {
        const loading = Loading.service({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        loading.close();
        flag = true;
        Element.Message.error(!res.msg ? "系统异常" : res.msg);
        if (res.data) {
            console.log(res.data)
        }
        return Promise.reject(res.msg);
    }
}, error => {
    const loading = Loading.service({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    loading.close();
    console.log(error)
    //判断返回的data是否为空
    if (error.response.data) {
        error.message = error.response.data.msg;
    }
    //判断返回的code是否为401（用户未登录）
    if (error.response.status === 401) {
        router.push("/login");
    }

    //duration：弹窗秒数
    Element.Message.error(!error.message ? "系统异常" : error.message);

    return Promise.reject(error);
})
export default request
